package com.lhh.adminlte.base;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.web.filter.authc.FormAuthenticationFilter;
import org.apache.shiro.web.filter.authz.AuthorizationFilter;
import org.apache.shiro.web.filter.authz.PermissionsAuthorizationFilter;
import org.apache.shiro.web.servlet.ShiroHttpServletRequest;

import javax.servlet.*;
import java.io.IOException;

/**
 * @Auther: hanhui.liu
 * @Date: 2018/5/24 14:25
 * @Description:
 */
public class PowerFilter extends FormAuthenticationFilter {
    @Override
    protected boolean isAccessAllowed(ServletRequest request, ServletResponse response, Object mappedValue) {
        boolean result = super.isAccessAllowed(request, response, mappedValue);
        if (result) {
            Subject subject = SecurityUtils.getSubject();
            ShiroHttpServletRequest shiroHttpServletRequest = (ShiroHttpServletRequest) request;
            String uri = shiroHttpServletRequest.getRequestURI();
            String context = shiroHttpServletRequest.getContextPath();
            String permission = uri.replace(context + "/", "");
            try {
                subject.checkPermission(permission);
            } catch (Exception e) {
                try {
                    response.setCharacterEncoding("UTF-8");
                    response.getWriter().write("权限不足:" + permission);
                    response.getWriter().flush();
                    response.getWriter().close();
                    result = false;
                } catch (IOException e1) {
                    e1.printStackTrace();
                }
            }
        }
        return result;
    }
}
